package com.hliushi.netty.server.handler;

import com.hliushi.netty.message.GroupChatRequestMessage;
import com.hliushi.netty.message.GroupChatResponseMessage;
import com.hliushi.netty.server.session.GroupSession;
import com.hliushi.netty.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * @author llhuang10
 * @date 2021/10/22 11:00
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String content = msg.getContent();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();

        // 根据 groupName 找到所有成员
        List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
        // 是否需要排除自己
        // boolean remove = membersChannel.remove(msg.getFrom());
        membersChannel.forEach(channel -> channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), content)));

    }
}
